/*
 * Copyright (c) 2015-2021, www.dibo.ltd (service@dibo.ltd).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.icesoft.system.data;

import com.icesoft.framework.core.config.Cons;
import com.icesoft.framework.core.data.access.DataAccessInterface;
import com.icesoft.system.auth.entity.LoginUser;
import com.icesoft.system.entity.User;
import com.icesoft.system.service.impl.SubOrgServiceImpl;
import com.icesoft.system.types.RoleTypeDictionary;
import com.icesoft.system.types.UserTypeDictionary;
import com.icesoft.system.util.SecurityUtils;
import com.icesoft.system.vo.UserVO;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 组织数据访问权限实现
 */
@Slf4j
public class DataAccessPermissionUserOrgImpl implements DataAccessInterface {

	@Resource
	private UserTypeDictionary userTypeDictionary;

	@Resource
	private RoleTypeDictionary roleTypeDictionary;

	@Resource
	private SubOrgServiceImpl subOrgService;

	@Override
	public List<? extends Serializable> getAccessibleIds(Class<?> entityClass, String fieldName) {
		LoginUser loginUser = SecurityUtils.getLoginUser();
		if (loginUser == null || SecurityUtils.isAdmin() || !(loginUser.getUser() instanceof User)) {
			return null;
		}
		List<Long> ids = new ArrayList<>();
		if (loginUser.getAccount().getUserType().equals(userTypeDictionary.system)) {
			UserVO user = (UserVO) loginUser.getUser();
			if (roleTypeDictionary.all.equals(user.getRole().getRoleType())) {
				ids.add(user.getCompanyId());
			}
			if (fieldName.contains(Cons.FieldName.companyId.name())) {
				ids.add(user.getCompanyId());
			} else if (fieldName.contains(Cons.FieldName.orgId.name())) {
				if (roleTypeDictionary.orgAll.equals(user.getRole().getRoleType())) {
					ids.addAll(subOrgService.findAllSubOrgIds(user.getOrgId()));
				}
				if (roleTypeDictionary.org.equals(user.getRole().getRoleType())) {
					if (user.getOrgId() != null) {
						ids.add(user.getOrgId());
					}
				}
				if (roleTypeDictionary.custom.equals(user.getRole().getRoleType())) {
					if (user.getRole().getOrgIdList() != null) {
						ids.addAll(user.getRole().getOrgIdList());
					}
				}
			}
		} else if (loginUser.getAccount().getUserType().equals(userTypeDictionary.wechat)) {
			return null;
		}
		if (ids.isEmpty()) {
			return null;
		}
		return ids;
	}

}
